import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useDesignerStore = defineStore('designer', () => {
  // 核心状态
  const isReady = ref(false)
  const isDirty = ref(false)
  const currentMode = ref('design') // design, preview, export
  const isLoading = ref(false)
  const error = ref(null)

  // 设计器配置
  const config = ref({
    gridSize: 20,
    snapEnabled: true,
    snapThreshold: 10,
    showGrid: true,
    showRulers: true,
    showGuides: true,
    autoSave: true,
    autoSaveInterval: 30000, // 30秒
    maxUndoSteps: 50,
    maxRedoSteps: 50
  })

  // 计算属性
  const canUndo = computed(() => {
    // 与history store联动
    return false
  })

  const canRedo = computed(() => {
    // 与history store联动
    return false
  })

  const isModified = computed(() => isDirty.value)

  // Actions
  const initialize = async () => {
    isLoading.value = true
    error.value = null
    
    try {
      // 初始化设计器
      await loadConfig()
      isReady.value = true
    } catch (err) {
      error.value = err.message
    } finally {
      isLoading.value = false
    }
  }

  const setMode = (mode) => {
    currentMode.value = mode
  }

  const setDirty = (dirty = true) => {
    isDirty.value = dirty
  }

  const updateConfig = (newConfig) => {
    config.value = { ...config.value, ...newConfig }
  }

  const loadConfig = async () => {
    // 从localStorage或API加载配置
    const savedConfig = localStorage.getItem('designer-config')
    if (savedConfig) {
      config.value = { ...config.value, ...JSON.parse(savedConfig) }
    }
  }

  const saveConfig = async () => {
    // 保存配置到localStorage或API
    localStorage.setItem('designer-config', JSON.stringify(config.value))
  }

  const reset = () => {
    isReady.value = false
    isDirty.value = false
    currentMode.value = 'design'
    isLoading.value = false
    error.value = null
  }

  return {
    // 状态
    isReady,
    isDirty,
    currentMode,
    isLoading,
    error,
    config,
    
    // 计算属性
    canUndo,
    canRedo,
    isModified,
    
    // Actions
    initialize,
    setMode,
    setDirty,
    updateConfig,
    loadConfig,
    saveConfig,
    reset
  }
})
